/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-02 08:42:12
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-28 08:39:08
 * @FilePath: \keep_motion_api\controller\sys\dictType.controller.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const { DictType } = require('@/models/sys');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置 multer 存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = './uploads';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}${ext}`);
  }
});
const upload = multer({ storage: storage });

// 查询字典类型
const getDictType = async (req, res) => {
  try {
    const { name, code, description, pageNum, pageSize } = req.query;
    const offset = (pageNum - 1) * pageSize;
    const limit = pageSize;
    const {rows, total} = await DictType.getDictType(name, code, description, offset, limit);
    res.status(200).send({rows, total});
  } catch (error) {
    res.status(500).json({ message: '查询字典类型失败', error });
  }
}
// 创建字典类型
const createDictType = async (req, res) => {
  try {
    const { name, code, description } = req.body;
    const dictType = await DictType.createDictType(name, code, description);
    res.status(200).json(dictType);
  } catch (error) {
    res.status(500).json({ message: '创建字典类型失败', error });
  }
}
// 修改字典类型
const updateDictType = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, code, description } = req.body;
    const dictType = await DictType.updateDictType(id, name, code, description);
    res.status(200).json(dictType);
  } catch (error) {
    res.status(500).json({ message: '修改字典类型失败', error });
  }
}
// 删除字典类型
const deleteDictType = async (req, res) => {
  try {
    const { id } = req.params;
    const dictType = await DictType.deleteDictType(id);
    res.status(200).json(dictType);
  } catch (error) {
    res.status(500).json({ message: '删除字典类型失败', error });
  }
}
// excal批量导入
const importDictType = async (req, res) => {
  try {
    upload.single('file')(req, res, async (err) => {
      if (err) {
        return res.status(500).json({ message: '文件上传失败', error: err });
      }
      const file = req.file;
      if (!file) {
        return res.status(400).json({ message: '未上传文件' });
      }
      const dictTypes = await DictType.importDictType(file.path);
      // 处理完文件后删除临时文件
      try {
        fs.unlinkSync(file.path);
        console.log('临时文件删除成功');
      } catch (unlinkError) {
        console.error('删除临时文件失败:', unlinkError);
      }
      res.status(200).json({message:'导入成功',count:dictTypes.length});
    });
  } catch (error) {
    res.status(500).json({ message: '导入字典类型失败', error });
  }
};
// 批量导出
const exportDictType = async (req, res) => {
  try {
    const { name, code, description } = req.query;
    const { buffer, filename } = await DictType.exportDictType( name, code, description );
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent(filename)}`);
    res.status(200).send(buffer);
  } catch (error) {
    res.status(500).json({ message: '导出字典类型失败', error });
  }
}



module.exports = {
  getDictType,
  createDictType,
  updateDictType,
  deleteDictType,
  importDictType,
  exportDictType,
}
